package com.mjh.config.handler;

import com.alibaba.fastjson2.JSONObject;
import com.mjh.constant.AuthConstants;
import com.mjh.model.R;
import com.mjh.model.SecurityUser;
import com.mjh.utils.JWTUtil;
import com.mjh.utils.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Duration;

/**
 * 登录成功处理器
 */
@Component
public class AppAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        // 获取用户信息
        SecurityUser user = (SecurityUser) authentication.getPrincipal();
        //生成jwt
        String jwt = JWTUtil.createJwt(JSONObject.toJSONString(user));
        // 将jwt存储到redis中
        redisTemplate.opsForValue().set(AuthConstants.TOKEN_REDIS_KEY_PREFIX + jwt, "", Duration.ofSeconds(AuthConstants.TOKEN_TIME));
        // 获取“记住我”状态
        Boolean rememberMe = Boolean.parseBoolean(request.getParameter("sss"));
        if (rememberMe) {
            redisTemplate.opsForValue().set(AuthConstants.TOKEN_REDIS_KEY_PREFIX +jwt,"", Duration.ofSeconds(AuthConstants.REMEMBER_ME_TOKEN_TIME));
        }
        //响应数据
        ResponseUtils.write(response, R.OK(jwt));
    }
}
